<template>
  <div class="app-container">
    <el-card>
      <!-- 搜索区域 -->
      <div class="filter-container">
        <el-input
          v-model="listQuery.username"
          placeholder="用户名"
          clearable
          style="width: 200px; margin-right: 10px"
          @keyup.enter="handleFilter"
        />
        <el-input
          v-model="listQuery.email"
          placeholder="邮箱"
          clearable
          style="width: 200px; margin-right: 10px"
          @keyup.enter="handleFilter"
        />
        <el-select
          v-model="listQuery.status"
          placeholder="状态"
          clearable
          style="width: 120px; margin-right: 10px"
        >
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
        <el-select
          v-model="listQuery.tenant_id"
          placeholder="租户"
          clearable
          style="width: 200px; margin-right: 10px"
        >
          <el-option
            v-for="tenant in tenantList"
            :key="tenant.id"
            :label="tenant.name"
            :value="tenant.id"
          />
        </el-select>
        <el-button type="primary" @click="handleFilter">搜索</el-button>
        <el-button type="info" @click="getList">强制刷新</el-button>
        <el-button
          type="success"
          @click="handleCreate"
          :disabled="userStore.isTest"
        >
          新增管理员
        </el-button>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="listLoading"
        :data="list"
        border
        stripe
        style="width: 100%; margin-top: 20px"
      >
        <el-table-column type="index" width="50" align="center" label="序号" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />

        <el-table-column prop="tenant_name" label="所属租户" min-width="150">
          <template #default="scope">
            <el-tag v-if="scope.row.tenant_name" type="primary">
              {{ scope.row.tenant_name }}
            </el-tag>
            <span v-else class="text-gray">未绑定</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="is_super"
          label="超级管理员"
          width="120"
          align="center"
        >
          <template #default="scope">
            <el-tag :type="scope.row.is_super ? 'danger' : 'info'">
              {{ scope.row.is_super ? "是" : "否" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="is_test"
          label="账号类型"
          width="100"
          align="center"
        >
          <template #default="scope">
            <el-tag :type="scope.row.is_test ? 'warning' : 'success'">
              {{ scope.row.is_test ? "测试账号" : "正式账号" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="last_login" label="最后登录" width="160" />
        <el-table-column prop="create_time" label="创建时间" width="160" />
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
              :disabled="userStore.isTest"
            >
              编辑
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="handleBindTenant(scope.row)"
              :disabled="userStore.isTest"
            >
              绑定租户
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="handleResetPassword(scope.row)"
              :disabled="userStore.isTest"
            >
              重置密码
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
              :disabled="
                userStore.isTest || scope.row.id === userStore.userInfo?.id
              "
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-show="total > 0"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="listQuery.per_page"
        v-model:current-page="listQuery.page"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 管理员编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="isCreate">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item label="所属租户" prop="tenant_id">
          <el-select
            v-model="form.tenant_id"
            placeholder="请选择租户"
            style="width: 100%"
          >
            <el-option label="无租户" :value="null" />
            <el-option
              v-for="tenant in tenantList"
              :key="tenant.id"
              :label="tenant.name"
              :value="tenant.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="超级管理员">
          <el-switch v-model="form.is_super" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 租户绑定对话框 -->
    <el-dialog title="绑定租户" v-model="tenantDialogVisible" width="400px">
      <el-form label-width="100px">
        <el-form-item label="管理员">
          <el-input :value="currentAdmin?.username" disabled />
        </el-form-item>
        <el-form-item label="当前租户">
          <el-input :value="currentAdmin?.tenant_name || '未绑定'" disabled />
        </el-form-item>
        <el-form-item label="选择租户">
          <el-select
            v-model="selectedTenantId"
            placeholder="请选择租户"
            style="width: 100%"
          >
            <el-option label="解除绑定" :value="null" />
            <el-option
              v-for="tenant in tenantList"
              :key="tenant.id"
              :label="tenant.name"
              :value="tenant.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="tenantDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitTenantBinding"
            :loading="submitting"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/store/user";
import {
  getAdminList,
  createAdmin,
  updateAdmin,
  deleteAdmin,
  updateAdminTenant,
  resetAdminPassword,
} from "@/api/admin";
import { getTenantList } from "@/api/tenant";

const userStore = useUserStore();

// 数据
const list = ref([]);
const tenantList = ref([]);
const total = ref(0);
const listLoading = ref(false);
const dialogVisible = ref(false);
const tenantDialogVisible = ref(false);
const dialogTitle = ref("");
const formRef = ref(null);
const isCreate = ref(false);
const submitting = ref(false);
const currentAdmin = ref(null);
const selectedTenantId = ref(null);

// 查询参数
const listQuery = reactive({
  page: 1,
  per_page: 10,
  username: "",
  email: "",
  tenant_id: null,
});

// 表单数据
const form = reactive({
  id: undefined,
  username: "",
  email: "",
  password: "",
  tenant_id: null,
  is_super: false,
});

// 表单验证规则
const rules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      min: 3,
      max: 20,
      message: "用户名长度在 3 到 20 个字符",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
  email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }],
};

// 获取管理员列表
const getList = async () => {
  console.log("开始获取管理员列表...");
  listLoading.value = true;
  try {
    console.log("发送请求参数:", listQuery);
    const response = await getAdminList(listQuery);
    console.log("完整响应:", response);

    if (response.code === 0) {
      console.log("响应成功，数据:", response.data);
      console.log("数据类型:", typeof response.data);
      console.log("是否为数组:", Array.isArray(response.data));

      // 检查数据格式
      if (Array.isArray(response.data)) {
        // 如果直接返回数组
        console.log("处理数组格式数据，长度:", response.data.length);
        list.value = [...response.data]; // 使用展开运算符确保响应式更新
        total.value = response.data.length;
      } else if (response.data && response.data.items) {
        // 如果返回包含items的对象
        console.log("处理对象格式数据，items长度:", response.data.items.length);
        list.value = [...response.data.items]; // 使用展开运算符确保响应式更新
        total.value = response.data.total || 0;
      } else {
        console.warn("未知的数据格式:", response.data);
        list.value = [];
        total.value = 0;
      }

      console.log("设置后的list.value:", list.value);
      console.log("设置后的total.value:", total.value);
      console.log("list.value长度:", list.value.length);

      // 强制触发响应式更新
      setTimeout(() => {
        console.log("延迟检查list.value:", list.value);
      }, 100);
    } else {
      console.error("响应失败:", response);
      ElMessage.error(response.message || "获取管理员列表失败");
    }
  } catch (error) {
    console.error("获取管理员列表失败:", error);
    ElMessage.error("获取管理员列表失败");
  } finally {
    listLoading.value = false;
    console.log("请求完成，loading状态:", listLoading.value);
  }
};

// 获取租户列表
const getTenants = async () => {
  try {
    const response = await getTenantList({ page: 1, limit: 1000 });
    if (response.code === 0) {
      tenantList.value = response.data.items || [];
    }
  } catch (error) {
    console.error("获取租户列表失败:", error);
  }
};

// 搜索
const handleFilter = () => {
  listQuery.page = 1;
  getList();
};

// 分页大小改变
const handleSizeChange = (val) => {
  listQuery.per_page = val;
  getList();
};

// 当前页改变
const handleCurrentChange = (val) => {
  listQuery.page = val;
  getList();
};

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: undefined,
    username: "",
    email: "",
    password: "",
    tenant_id: null,
    is_super: false,
  });
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 新增管理员
const handleCreate = () => {
  resetForm();
  isCreate.value = true;
  dialogTitle.value = "新增管理员";
  dialogVisible.value = true;
};

// 编辑管理员
const handleEdit = (row) => {
  resetForm();
  isCreate.value = false;
  dialogTitle.value = "编辑管理员";
  Object.assign(form, {
    id: row.id,
    username: row.username,
    email: row.email,
    tenant_id: row.tenant_id,
    is_super: row.is_super,
  });
  dialogVisible.value = true;
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    submitting.value = true;

    const submitData = { ...form };
    delete submitData.id;

    let response;
    if (isCreate.value) {
      response = await createAdmin(submitData);
    } else {
      response = await updateAdmin(form.id, submitData);
    }

    if (response.code === 0) {
      ElMessage.success(isCreate.value ? "创建成功" : "更新成功");
      dialogVisible.value = false;
      getList();
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("提交表单失败:", error);
    ElMessage.error("操作失败");
  } finally {
    submitting.value = false;
  }
};

// 重置密码
const handleResetPassword = async (row) => {
  try {
    const { value: newPassword } = await ElMessageBox.prompt(
      `请输入管理员 "${row.username}" 的新密码`,
      "重置密码",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputType: "password",
        inputValidator: (value) => {
          if (!value) {
            return "密码不能为空";
          }
          if (value.length < 6) {
            return "密码长度不能少于6位";
          }
          return true;
        },
      }
    );

    const response = await resetAdminPassword(row.id, newPassword);
    if (response.code === 0) {
      ElMessage.success("密码重置成功");
    } else {
      ElMessage.error(response.message || "密码重置失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("重置密码失败:", error);
      ElMessage.error("密码重置失败");
    }
  }
};

// 删除管理员
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除管理员 "${row.username}" 吗？删除后不可恢复！`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const response = await deleteAdmin(row.id);
    if (response.code === 0) {
      ElMessage.success("删除成功");
      getList();
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除管理员失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

// 绑定租户
const handleBindTenant = (row) => {
  currentAdmin.value = row;
  selectedTenantId.value = row.tenant_id;
  tenantDialogVisible.value = true;
};

// 提交租户绑定
const submitTenantBinding = async () => {
  try {
    submitting.value = true;
    const response = await updateAdminTenant(
      currentAdmin.value.id,
      selectedTenantId.value
    );

    if (response.code === 0) {
      ElMessage.success("租户绑定成功");
      tenantDialogVisible.value = false;
      getList();
    } else {
      ElMessage.error(response.message || "绑定失败");
    }
  } catch (error) {
    console.error("绑定租户失败:", error);
    ElMessage.error("绑定失败");
  } finally {
    submitting.value = false;
  }
};

// 初始化
onMounted(() => {
  console.log("组件挂载，开始获取数据");
  getList();
  getTenants();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.text-gray {
  color: #909399;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
